package com.sas.until;

import java.io.IOException;

import javax.servlet.Filter;  
import javax.servlet.FilterChain;  
import javax.servlet.FilterConfig;  
import javax.servlet.ServletException;  
import javax.servlet.ServletRequest;  
import javax.servlet.ServletResponse;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
import javax.servlet.http.HttpSession;  
  
import org.apache.commons.lang3.StringUtils;  
  
/**
 *
 *2017-11-2
 *胡其安
 *
 *
 *
 */
public class SessionFilter implements Filter{
	/** 
	* 需要排除的页面 
	*/  
	private String excludedPages;  
	  
	private String[] excludedPageArray;  
	/** 
	* @see Filter#destroy() 
	*/  
	public void destroy() {  
	return;  
	}  
	  
	/** 
	* 对session进行判断当前访问是否有登录 
	*/  
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {  
	
boolean isExcludedPage = false; 
StringBuffer server = ((HttpServletRequest) request).getRequestURL();
	for (String page : excludedPageArray) {//判断是否在过滤url之外  
//		System.out.println("根目录"+((HttpServletRequest) request).getServletPath()+"="+page);
	if(((HttpServletRequest) request).getServletPath().equals(page)){  
	isExcludedPage = true;  
	break;  
	}  
	}     
//	System.out.println("真假?"+(isExcludedPage));
//	System.out.println("后方判断包含"+(server.toString().endsWith(".css")));
//	System.out.println("真假?"+(server.toString().endsWith(".js")));
//	System.out.println("真假?"+(server.toString().endsWith(".png")));
	Boolean tu=(isExcludedPage||server.toString().endsWith(".css")||server.toString().endsWith(".js")||server.toString().endsWith(".png"));
//	System.out.println("真假"+tu);
	if (tu) {//在过滤url之外   为真不拦截		
	chain.doFilter(request, response);  
//	System.out.println("不拦截1");
	} else {//不在过滤url之外，判断session是否存在  
	HttpSession session = ((HttpServletRequest) request).getSession();  
	if (session == null ||  session.getAttribute("user") == null) {  
	//	 response.sendRedirect(request.getContextPath() + "/WEB-INF/login.jsp");
	((HttpServletResponse) response).sendRedirect("/test_1/login.jsp"); 
	//System.out.println("拦截21");
	} else {  
	chain.doFilter(request, response);  
	//System.out.println("不拦截22");
	}  
	}  
	
	}  
	  
	/** 
	* 初始化函数，获取需要排除在外的url 
	*/  
	public void init(FilterConfig fConfig) throws ServletException {  
	excludedPages = fConfig.getInitParameter("excludedPages");  
	if (StringUtils.isNotEmpty(excludedPages)) { 
		
	excludedPageArray = excludedPages.split(",");
	
	}  
	return;  
	}  
}
